package com.pink.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pink.entity.config.AppConfig;
import com.pink.entity.dto.UserDto;
import com.pink.entity.enums.ResponseCodeEnum;
import com.pink.entity.enums.UserStatusEnum;
import com.pink.entity.enums.UserVerifyStatusEnum;
import com.pink.entity.query.UserQuery;
import com.pink.entity.vo.response.UserInformVo;
import com.pink.exception.BusinessException;
import com.pink.mappers.UserMapper;
import com.pink.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDto> implements UserService{

    @Resource
    AppConfig appConfig;

    @Resource
    UserMapper userMapper;

    @Override
    // 根据用户名或邮箱查找用户
    public UserDto findAccountByNameOrEmail(String username) {
        return this.query()
                .eq("username",username).or()
                .eq("email",username)
                .one();
    }

    @Override
    //用户注册
    public String register(UserDto user) {
        // 判断用户是否为空
        if(user == null) throw  new BusinessException(ResponseCodeEnum.CODE_600.getCode(), ResponseCodeEnum.CODE_600.getMessage());
        // 判断用户信息是否完整
        if(user.getUsername() == null || user.getPassword() == null|| user.getEmail() == null){
            throw new BusinessException("用户信息不完整");
        }
        // 根据邮箱查询用户
        UserDto dbUser = this.query().eq("email", user.getEmail()).one();
        // 判断邮箱是否已被注册
        if(dbUser != null) throw new BusinessException("邮箱已被注册");
        // 根据用户名查询用户
        dbUser = this.query().eq("username", user.getUsername()).one();
        // 判断用户名是否已被注册
        if(dbUser != null) throw new BusinessException("用户名已被注册");
        // 对密码进行加密
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        // 设置用户头像
        user.setAvatarUrl(appConfig.getAvatarUrl());
        // 设置用户状态
        user.setUserStatus(UserStatusEnum.NORMAL.getCode());
        // 设置邮箱状态
        user.setEmailStatus(UserVerifyStatusEnum.NORMAL.getCode());
        // 保存用户信息
        this.save(user);
        return "注册成功";
    }

    @Override
    // 更新用户最后登录时间
    public void updateLastLoginTime(Integer userId) {
        this.update().set("last_login", new Date()).eq("user_id", userId).update();
    }

    @Override
    //获取用户信息
    public UserInformVo findAccountByNameOrUsername(String username) {
        // 根据用户ID查询用户信息
        if(username == null) throw new BusinessException("用户不存在");
        UserDto userInformVo = this.query().eq("username",username).one();
        // 如果查询结果为空，抛出异常
        if(userInformVo == null) throw new BusinessException("用户不存在");
        // 创建UserInformVo对象
        UserInformVo user = new UserInformVo();
        // 将查询结果复制到UserInformVo对象中
        BeanUtils.copyProperties(userInformVo,user);
        // 返回UserInformVo对象
        return user;
    }

    @Override
    public UserQuery findUserQueryList(int pageNo, int pageSize, String username, Integer userRole) {
        List<UserDto> userList = null;
        if (userRole == null||username == null||username == "") {//查询所有用户
            userList = this.list();
        }
        if(username == null||username == ""){//查询指定用户角色
            userList = this.list(new QueryWrapper<UserDto>().eq("user_role", userRole));
        }
        if(userRole == null) {//查询指定用户名
            userList = this.list(new QueryWrapper<UserDto>().like("username", username));
        }
        if (userRole != null && username != null && username != "") {//查询指定用户名和用户角色
            userList = this.list(new QueryWrapper<UserDto>().eq("user_role", userRole).like("username", username));
        }
        UserQuery userQuery = new UserQuery();//查询结果
        userQuery.setPageSize(pageSize);//每页显示条数
        userQuery.setPageNo(pageNo);//当前页
        userQuery.setTotalCount(userList.size());//总条数
        userQuery.setPageTotal(userList.size() / pageSize + 1);//总页数
        if(userList != null && userList.size() >= pageSize){
            //对数据进行分页
            userList = userList.subList((pageNo - 1) * pageSize, (pageNo - 1) * pageSize + pageSize);
        }
        //对数据的密码设置为空
        for (UserDto user : userList) {
            user.setPassword(null);
        }
        userQuery.setList(userList);//用户列表
        return userQuery;
    }

    @Override
    public String deleteUser(Integer id) {
        if(id == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600.getCode(), ResponseCodeEnum.CODE_600.getMessage());
        }else{
            //按userId删除用户信息
            this.userMapper.removeByUserId(id);
            return "删除成功";
        }
    }

    @Override
    public String updateUser(UserDto user) {
        if(user == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600.getCode(), ResponseCodeEnum.CODE_600.getMessage());
        }
        if(user.getPassword() != null && user.getPassword() != ""){
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        }
        //按userId更新用户信息
        this.update(user,new QueryWrapper<UserDto>().eq("user_id", user.getUserId()));
        return "修改成功";
    }

    @Override
    public String addUser(UserDto user) {
        if(user == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600.getCode(), ResponseCodeEnum.CODE_600.getMessage());
        }
        if(user.getAvatarUrl() == null){
            user.setAvatarUrl(appConfig.getAvatarUrl());
        }
        user.setLastLogin(null);
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        this.save(user);
        return "添加成功";
    }

    @Override
    public UserDto getUserByuserId(Integer userId) {
        return this.query().eq("user_id", userId).one();
    }

    @Override
    public String updatePassword(Integer userId,UserDto user, String repPassword) {
        //查询用户
        UserDto userDto = this.query().eq("user_id", userId).one();
        if(userDto == null){
            throw new BusinessException("用户不存在");
        }
        if(repPassword != null && repPassword != ""){
            //和数据库比对密码
            if(!new BCryptPasswordEncoder().matches(user.getPassword(), userDto.getPassword())){
                throw new BusinessException("旧密码错误");
            }
            //修改密码
            userDto.setPassword(new BCryptPasswordEncoder().encode(repPassword));
        }
        this.update(user,new QueryWrapper<UserDto>().eq("user_id", userId));
        return "修改成功";
    }
}
